package com.xhu.water_supply.web.controller;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xhu.water_supply.dto.*;
import com.xhu.water_supply.entity.Administrator;
import com.xhu.water_supply.service.AdminInfoService;
import com.xhu.water_supply.web.vo.AdminInfoVO;
import com.xhu.water_supply.web.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@Api(tags = "管理员信息控制器")
@RequestMapping("api/admininfo")
public class AdminInfoController {
    @Autowired
    private AdminInfoService adminInfoService;

    @ApiOperation(value = "修改密码接口")
    @PostMapping("modifypassword")
    public Result modifyPassword(ModifyPasswordDTO modifyPasswordDTO){
        Administrator administrator=adminInfoService.getByAccount(modifyPasswordDTO.getAccount());
        if(SecureUtil.md5(modifyPasswordDTO.getOldpassword()).equals(administrator.getPassword())){
            //administrator.setPassword(modifyPasswordDTO.getNewpassword1());
            String pwdMd5 = SecureUtil.md5(modifyPasswordDTO.getNewpassword1());
            administrator.setPassword(pwdMd5);
            int a=adminInfoService.modifyAdminInfoByAccount(administrator);
            if(a>0)
                return ResultUtils.returnSuccess(ResultEnum.SUCCESS_UPDATE_PASSWORD.getMsg());
            else
                return ResultUtils.returnFail(ResultEnum.FAIL_UPDATE_PASSWORD.getMsg());
        }
        else
            return ResultUtils.returnFail(ResultEnum.FAIL_OLD_PASSWORD.getMsg());
    }

    @ApiOperation(value = "分页查询全部管理员信息接口")
    @PostMapping("allAdminInfo")
    public PageVO<Administrator> allAdminInfo(AdminInfoAllDTO adminInfoAllDTO){
        //分页插件
        Page<Administrator> page=PageHelper.startPage(adminInfoAllDTO.getPageNO(), adminInfoAllDTO.getPageSize());
        List<Administrator> administratorList=adminInfoService.getAllAdminInfo();
        PageVO<Administrator> pageVO = new PageVO<>(administratorList, adminInfoAllDTO.getPageNO(), adminInfoAllDTO.getPageSize(),(int)page.getTotal());
        return pageVO;
    }

    @ApiOperation(value = "分页模糊查询管理员信息接口")
    @PostMapping("queryAdminInfo")
    public Result<PageVO<Administrator>> queryAdminInfo(AdminInfoQueryDTO adminInfoQueryDTO){
        Page<Administrator> page=PageHelper.startPage(adminInfoQueryDTO.getPageNO(), adminInfoQueryDTO.getPageSize());
        List<Administrator> administratorList=adminInfoService.fuzzySearchAdminInfo(adminInfoQueryDTO.getSearchStr(),adminInfoQueryDTO.getSelect());
        PageVO<Administrator> pageVO = new PageVO<>(administratorList, adminInfoQueryDTO.getPageNO(), adminInfoQueryDTO.getPageSize(),(int)page.getTotal());
        return ResultUtils.returnSuccess(ResultEnum.SUCCESS_QUERY_ADMIN_INFO.getMsg(),pageVO);
    }

    @ApiOperation(value = "查询被修改管理员信息接口")
    @GetMapping("getModifyAdminInfo")
    public AdminInfoVO getModifyAdminInfo(String id){
        Administrator administrator = adminInfoService.getById(id);
        AdminInfoVO adminInfoVO=new AdminInfoVO();
        //Administrator转化为VO对象
        BeanUtils.copyProperties(administrator,adminInfoVO);
        return adminInfoVO;
    }

    @ApiOperation(value = "修改管理员信息接口")
    @PostMapping("modifyAdminInfo")
    public Result modifyAdminInfo(AdminInfoModifyDTO adminInfoModifyDTO) throws IOException {
        Administrator administrator = adminInfoService.getById(adminInfoModifyDTO.getId());
        BeanUtils.copyProperties(adminInfoModifyDTO, administrator);
        String pwdMd5 = SecureUtil.md5(adminInfoModifyDTO.getPassword());
        //修改照片
        if(adminInfoModifyDTO.getPicture().length()>64){
            String fileBase64 = adminInfoModifyDTO.getPicture();
            String s[] = fileBase64.substring(5, fileBase64.indexOf(";")).split("/");
            String type = s[1];
            //时间戳作为文件名字
            long timeStamp = System.currentTimeMillis();
            String stamp = String.valueOf(timeStamp).substring(2, 13);
            String file = "D:\\images_server" + "\\" + stamp + "." + type;
            FileOutputStream fop = null;
            BASE64Decoder decoder = new BASE64Decoder();
            // 进行base64解码
            String img = fileBase64.substring(fileBase64.indexOf(',') + 1);
            System.out.println(img);
            byte[] buffer = decoder.decodeBuffer(img);
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] < 0) {
                    buffer[i] += 256;
                }
            }
            fop = new FileOutputStream(file);
            fop.write(buffer);
            fop.flush();
            fop.close();
            administrator.setPicture(stamp + "." + type);
        }
        else{
            String url=adminInfoModifyDTO.getPicture();
            String imgName=url.substring(url.lastIndexOf("/")+1,url.length());
            administrator.setPicture(imgName);
        }
        administrator.setPassword(pwdMd5);
        int a=adminInfoService.modifyAdminInfoById(administrator);
        if(a>0)
            return ResultUtils.returnSuccess(ResultEnum.SUCCESS_UPDATE_ADMIN_INFO.getMsg());
        else
            return ResultUtils.returnFail(ResultEnum.FAIL_UPDATE_ADMIN_INFO.getMsg());
    }

    @ApiOperation(value = "通过id删除管理员接口")
    @GetMapping("deleteAdminInfoById")
    public Result deleteAdminInfoById(String id){
        int a = adminInfoService.deleteAdminInfoById(id);
        if(a>0)
            return ResultUtils.returnSuccess(ResultEnum.SUCCESS_DELETE_ADMIN.getMsg());
        else
            return ResultUtils.returnFail(ResultEnum.FAIL_DELETE_ADMIN.getMsg());
    }

    @ApiOperation(value = "添加管理员接口")
    @PostMapping("addAdminInfo")
    public Result addAdminInfo(AdminInfoAddDTO adminInfoAddDTO) throws IOException {
        Administrator administrator=new Administrator();
        BeanUtils.copyProperties(adminInfoAddDTO,administrator);
        //查询账号是否重复
        if(adminInfoService.getByAccount(adminInfoAddDTO.getAccount())!=null)
            return ResultUtils.returnFail(ResultEnum.FAIL_ADD_ACCOUNT_REPEAT.getMsg());
        //获取当前时间
        Date date = new Date();
        administrator.setDate(date);
        //修改权限对应值写入数据库
        if(administrator.getAuthority().equals("超级管理员"))
            administrator.setAuthority("a");
        else
            administrator.setAuthority("b");
        //时间戳做为id,截取11位
        long timeStamp = System.currentTimeMillis();
        String stamp=String.valueOf(timeStamp).substring(2,13);
        administrator.setId(stamp);
        //密码md5加密
        String pwdMd5 = SecureUtil.md5(administrator.getPassword());
        administrator.setPassword(pwdMd5);
        //添加照片
        //照片上传本地服务器 http://images.server.com/ 对应文件夹D:\images_server
        String fileBase64=adminInfoAddDTO.getPicture();
        String s[]=fileBase64.substring(5,fileBase64.indexOf(";")).split("/");
        String type=s[1];
        String file = "D:\\images_server" + "\\" + stamp+"."+type;
        FileOutputStream fop = null;
        BASE64Decoder decoder = new BASE64Decoder();
        // 进行base64解码
        String img=fileBase64.substring(fileBase64.indexOf(',') + 1);
        System.out.println(img);
        byte[] buffer = decoder.decodeBuffer(img);
        for(int i = 0; i < buffer.length; ++i) {
            if (buffer[i] < 0) {
                buffer[i] += 256;
            }
        }
        fop = new FileOutputStream(file);
        fop.write(buffer);
        fop.flush();
        fop.close();
        administrator.setPicture(stamp+"."+type);
        //添加
        int a=adminInfoService.addAdminInfo(administrator);
        if(a>0)
            return ResultUtils.returnSuccess(ResultEnum.SUCCESS_ADD_ADMIN.getMsg());
        else
            return ResultUtils.returnFail(ResultEnum.FAIL_ADD_ADMIN.getMsg());
    }


    @ApiOperation(value = "确认管理员权限接口")
    @GetMapping("affirmAuthority")
    public String uploadImg(String account)  {
        Administrator administrator = adminInfoService.getByAccount(account);
        administrator.getAuthority();
        return administrator.getAuthority();
    }

}
